
var defaultParameter = {
    pageNumber: 1,
    pageSize: 20
};

var modalType="add";

var fileInfo =null;
var rowIndex;

var tmpfiles;//文件上传下载
var client = new com.im.common.ajax();
var bidMap={};

var file = new com.im.common.file();
tmpfiles = file.activate(1);
$('#common_file').val('');
$('#common_file_name').hide();
$("#common_file_bnt").text("添加招标文件");
function initTable(){

    var columns=[[
        {field:'全选',title:"全选",width:30,checkbox:true,width:20,fitColumns:true},
        {field:'impleProjName',title:"实施项目",width:110,
            formatter: function(value,row,index){
                console.log(row);
                return row.implementProject.impleProjName;
            }
        },
        {field:'orgId',title:"建设单位",fitColumns:true,width:100,
            formatter: function(value,row,index){
                return row.implementProject.developOrgName;
            }
        },
        {field:'purchPlanName',title:'采购计划',fitColumns:true,width:140,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null){
                    return "["+row.purchasePlan.purchPlanNum+"]"+row.purchasePlan.purchPlanName;
                }else{
                    return "";
                }

            }
        },
        {field:'purchWay',title:'采购方式',fitColumns:true,width:100,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null){
                    return row.purchasePlan.planTypeName;
                }else{
                    return "";
                }

            }
        },
        {field:'prepayTotal',title:"采购预算(万元)",fitColumns:true,width:150,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null) {
                    return row.purchasePlan.prepayTotal;
                }else{
                    return "";
                }
            }
        },
        {field:'agentOrg',title:"采购代理机构",fitColumns:true,width:140,
            formatter: function(value,row,index){
                if(row.purchasePlan!=null) {
                    return row.purchasePlan.agentName;
                }else{
                    return "";
                }
            }
        },
        {field:'tenderCode',title:"标书名称",fitColumns:true,width:150,
            formatter: function(value,row,index){
                if(row.docManage!=null) {
                    return "["+row.docManage.docCode+"]"+row.docManage.docName;
                }else{
                    return "";
                }
            }
        },
        {field:'finishDate',title:"标书定稿时间",fitColumns:true,width:150,
            formatter: function(value,row,index){
                if(row.docReviewResult!=null) {
                    return row.docReviewResult.finalDt;
                }else{
                    return "";
                }
            }
        },
        {field:'openDate',title:"开标时间",fitColumns:true,width:100,
            formatter: function(value,row,index){
                if(row.result!=null) {
                    return row.result.openDt;
                }else{
                    return "";
                }
            }
        },
        {field:'orgName',title:"中标单位",fitColumns:true,width:100,
        },

        {field:'money',title:"中标金额(万元)",fitColumns:true,width:150,
        },
        {field:'noticeCode',title:"通知书编号",fitColumns:true,width:120,
            formatter: function(value,row,index){
                if(row.noticeManage!=null) {
                    return row.noticeManage.noticeCode;
                }else{
                    return "";
                }
            }
        },
        {field:'noticeName',title:"通知书名称",fitColumns:true,width:120,
            formatter: function(value,row,index){
                if(row.noticeFile!=null) {
                    return "<span style='cursor:pointer'><u><a onclick='downloadFile(\""+row.noticeFile.filePath+"\",\""+row.noticeFile.attachFullName+"\")'>"+row.noticeFile.attachFullName+"</a></u></span><br>";
                }else{
                    return "";
                }

            }
        },
        {field:'openDt',title:"公示时间",fitColumns:true,width:100,
            formatter: function(value,row,index){
                if(row.noticeManage!=null) {
                    return row.noticeManage.publicityDt;
                }else{
                    return "";
                }
            }
        },
        {field:'description',title:"备注",fitColumns:true,width:100,
            formatter: function(value,row,index){
                if(row.noticeManage!=null) {
                    return row.noticeManage.description;
                }else{
                    return "";
                }
            }
        },
        {field:'statusCdName',title:"状态",fitColumns:true,width:70,
            formatter: function(value,row,index){
                if(row.noticeManage!=null) {
                    return row.noticeManage.statusCdName;
                }else{
                    return "";
                }
            }
        },
        {field:'operation',title:"操作",width:80,
            formatter: function(value,row,index){
                if(row.noticeManage!=null &&row.noticeManage.statusCd==20) {
                    return '';
                }  else{
                    return '<a class="edit" href="javascript:void(0)" title="编辑" onclick="updateLetterModal('
                        + index
                        + ')"> <i class="fa fa-edit"></i></a>'
                        +
                        '<a class="remove" href="javascript:void(0)" title="删除" onclick="delNoticeManageConfirm('
                        + index
                        + ')"><i class="fa fa-trash"></i></a>';
                }
            }},
    ]];

    $('#letterList').datagrid({
        url:'/InfoManageWeb/noticeManageService/queryNoticeManageListForUI',
        method:'post',
        dataType : 'json',
        queryParams:defaultParameter,
        pagination:true,
        nowrap:false,
        fitColumns:true,
        columns:columns,
        onBeforeLoad : function(param){
            console.log(param);
            for (var key in param) {
                if(key=="rows"){
                    delete param[key];
                }
            }
        },
        loadFilter:function(data){
            if(data.resultCode!=0){
                toastr.error(data.resultMsg);
                return null;
            }else{
                return data.result;
            }
        },
        onLoadSuccess: function(data) {
            if (data.rows.length > 0) {
                var dg = $('#letterList');
                var mark=1;
                for (var i=1; i < dg.datagrid("getRows").length; i++) {
                    if (dg.datagrid("getRows")[i].implementProject.impleProjName== dg.datagrid("getRows")[i-1].implementProject.impleProjName) {
                        mark += 1;
                        dg.datagrid('mergeCells',{
                            index: i+1-mark,
                            field: 'impleProjName',
                            rowspan:mark
                        });
                    }else{
                        mark=1;
                    }
                }
                mark=1;
                for (var i=1; i < dg.datagrid("getRows").length; i++) {
                    if (dg.datagrid("getRows")[i].implementProject.developOrgName== dg.datagrid("getRows")[i-1].implementProject.developOrgName) {
                        mark += 1;
                        dg.datagrid('mergeCells',{
                            index: i+1-mark,
                            field: 'orgId',
                            rowspan:mark
                        });
                    }else{
                        mark=1;
                    }
                }
            }
        }
    });
    var p = $('#letterList').datagrid('getPager');
    $(p).pagination({
        pageSize: 20,//每页显示的记录条数，默认为10
        pageList: [10,20,30],//可以设置每页记录条数的列表
        beforePageText: '第',//页数文本框前显示的汉字
        afterPageText: '页    共 {pages}  页',
        displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
        onSelectPage:function(pageNumber, pageSize){
            defaultParameter.pageNumber=pageNumber;
            defaultParameter.pageSize=pageSize;
            defaultParameter.orgId=$("#orgId").val();
            defaultParameter.planProjClass=$("#planProjClass").val();
            defaultParameter.implProjectId=$("#implProjectId").val();
            defaultParameter.statusCdQry=$("#statusCdQry").val();
            $('#letterList').datagrid('reload',defaultParameter);
        }
    });
}

function downloadFile(path,realName){
    location.href="/FileManageWeb/fileController/downloadFile?fileName="+path+"&realName="+encodeURI(encodeURI(realName));
}

function initPlan(){
    $("#belongPlan").constantCommpent({
        elmIdSel : "belongPlan",//需要展示的位置下拉框
        constParamCode : "PLAN_PROJ_CLASS",//需要加载的常量编码
        callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
        }
    });
}

function initImpleProj(){

    $("#implProjectInfo").empty();
    $("#implProjectInfo").val("").trigger("change");

    var planProjClassInfo= $('#planProjClassInfo').val();
    var orgIdInfo = $("#orgIdInfo").val();
    var client = new com.im.common.ajax();
    var param={
        "planProjClass":planProjClassInfo,
        "developOrg":orgIdInfo,
    }
    var result = client.callAsJson("tenderPreparationService/querySuccTendInfoList",param);

    result.result.unshift({'impleProjId':'','impleProjName':'全部'});
    $.each( result.result, function (i) {
        $('#implProjectInfo').append("<option value=" + result.result[i].impleProjId +">" +result.result[i].impleProjName + "</option>");

    });
    $("#tenderInfoId").select2({});

}

function initPurchPlan(param){
    $('#purchPlan').empty();
    var client = new com.im.common.ajax();
    var result = client.callAsJson("purchaseService/queryPurchasePlanByParam",param);
    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        result.result.unshift({'purchPlanId':'','purchPlanName':'全部'});
        $.each( result.result, function (i) {
            $('#purchPlan').append("<option value=" + result.result[i].purchPlanId + ">" +result.result[i].purchPlanName + "</option>");

        });
        $("#purchPlan").select2({});
    }

}

function initFileType(){
    var client = new com.im.common.ajax();
    var fileTypeList = client.callAsJson("commonService/queryTabColParam", {tabName:'T_FILE_UPLOAD',colName:'FILE_TYPE'}).result;
    console.log(fileTypeList);
    fileTypeList.unshift({'colVal':'','colValName':'全部'});
    $.each(fileTypeList, function (i) {
        $('#fileType').append("<option value=" + fileTypeList[i].colVal + ">" +fileTypeList[i].colValName + "</option>");

    });
    $("#fileType").select2({});
}

function uploadFile(){
    var formData = new FormData($('#letterForm')[0]);
    $.ajax({
        url: '/FileManageWeb/fileController/batchUploadFiles',
        type: 'POST',
        cache: false,
        data: formData,
        contentType : false,
        processData: false,
        success : function(data) {
            var result = JSON.parse(data);
            var info=result.result[0];
            // fileInfo.uploadName=info.attachFullName;
            // fileInfo.fileSuffix=info.attachSuffix;
            // fileInfo.uploadSize=info.attachSize;
            // fileInfo.filePath=info.attachPath;
            // fileInfo.uploadDt=info.uploadDt;
            fileInfo=info;
            console.log(fileInfo);
            if (result.resultCode == '0') {
                result.success = true;
            } else {
                result.success = false;
            }
            console.log(result);
        },
    });
}

function disableField(){
//   $("#orgIdInfo").attr("disabled", true);
//   $("#planProjClassInfo").attr("disabled", true);
//    $("#tenderInfoId").attr("disabled", true);
//    $("#implProjectInfo").attr("disabled", true);
//    $("#purchPlan").attr("disabled", true);
    if(modalType=='update'){
        $("#tenderInfoId").prop("disabled", true);
    }

}

function ableField(){
//    $("#orgIdInfo").attr("disabled", false);
//    $("#planProjClassInfo").attr("disabled", false);
//    $("#tenderInfoId").attr("disabled", false);
//    $("#implProjectInfo").attr("disabled", false);
//    $("#purchPlan").attr("disabled", false);
    $("#tenderInfoId").prop("disabled", false);
}

function updateLetterModal(index){
    rowIndex =index;
    var row = $('#letterList').datagrid('getData').rows[index];
    $('#addEditModal').modal("show");
    getBidDocInfo();
    if(row.noticeManage!=null){
        modalType='update';
        $("#noticeManageId").val(row.noticeManage.noticeManageId);
        $("#noticeNo").val(row.noticeManage.noticeCode);
        $("#contractId").val(row.noticeManage.contractId);
        $("#tenderInfoId").append("<option value=" + row.tenderInfo.tenderInfoId +">["+row.docManage.docCode+"]" +row.docManage.docName + "</option>");
        $("#tenderInfoId").trigger('change');
    }else{
        newNoticeInfo();
    }

    $('#addEditModal .modal-title').html('通知书修改');
    // $("#orgIdInfo").val(row.developOrgId).trigger("change");

    if(row.noticeFile!=null){
        $("#myFileName").val(row.noticeFile.attachFullName);
    }
    var oldFile=[];
    if(row.fileList!=null && row.fileList.length>0){
        for(var i=0;i<row.fileList.length;i++){
            var info=row.fileList[i];
            oldFile.push({"fileSuffix":info.attachSuffix,"uploadName":info.attachFullName.substr(0,info.attachFullName.lastIndexOf(".")),"uploadId":info.uploadId});
        }
    }
    // var oldFile=[{"fileSuffix":"doc","filePath":"/12/123","uploadName":"123"},{"fileSuffix":"doc","filePath":"/12/123","uploadName":"456"}];
    file.activate(1,oldFile);
    $("#common_file_bnt").text("添加招标文件");

//  $("#implProjectInfo").val(row.implementProject.impleProjId).change();
    if(row.purchasePlan!=null){
        $("#purchPlanId").val(row.purchasePlan.purchPlanId);
        $("#purchPlan").val(row.purchasePlan.purchPlanNum+row.purchasePlan.purchPlanName);
        $("#money").val(row.purchasePlan.prepayTotal);
        $("#prepayTotal").val(row.purchasePlan.prepayTotal);
    }

//  $("#tenderInfoArea").empty();
//  $("#tenderInfoArea").attr("type","update");
//  $("#tenderInfoArea").append("<label  for=\"tenderInfoId\" class=\"control-label\">招标名称：</label>\n" +
//             " <input type=\"text\" class=\"form-control\" disabled id=\"tenderInfoName\"  name=\"tenderInfoName\"/><input type=\"text\" class=\"form-control hidden\" id=\"tenderInfoId\"  name=\"tenderInfoId\"/>");


    if(row.implementProject!=null){
        $("#implProjectInfo").val(row.implementProject.impleProjName);
        $("#implProId").val(row.implementProject.impleProjId);
    }


    if(row.noticeManage!=null){
        $("#tenderInfoId").val(row.result.tenderInfoId);
        $("#tenderInfoName").val("["+row.docManage.docCode+"]"+row.docManage.docName);
        $("#openDt").val(row.noticeManage.publicityDt);
        $("#fileCount").val(row.noticeManage.fileRec);
        $("#description").val(row.noticeManage.description);
        $("#statusCd").val(row.noticeManage.statusCd).change();
    }



    if(row.orgId!=null){
        $("#orgList").val(row.orgId).change();
    }


    if(row.money!=null){
        $("#money").val(row.money);
    }
    disableField();

    $("#money").focus(function (){
        $("#money").val("");
    })



    // var client = new com.im.common.ajax();
    // var param={};
    // param.seqType="3";
    // param.seqArg=impleProjectId;
    // var result = client.callAsJson("commonService/getSeqForRule",param);
    // if(result.resultCode!=0){
    //   toastr.error(result.resultCode);
    // }else{
    //   console.log(result.result.seq);
    //   $("#tenderCode").val(result.result.seq);
    // }

}

function _callBackOrg(staffId,staffName){
    $("#orgInfoId").val(staffId);
}
function getBidDocInfo(){
    var row = $('#letterList').datagrid('getData').rows[rowIndex];
    $("#tenderInfoId").empty();
    $("#tenderInfoId").val("").trigger("change");
    //根据采购计划id获取标书信息
    bidMap={};
    // var purchPlanId= $('#purchPlan').val();
    // var impleProjId = $("#implProjectInfo").val();
    // var noticeManageId = $("#noticeManageId").val();
    var client = new com.im.common.ajax();
    var param={
        // "purchPlanId":purchPlanId,
        // "impleProjId":impleProjId,
        //  "noticeManageId":noticeManageId,
    }
    if (row.docManage != null) {
        $("#tenderInfoId").append("<option value=" + row.tenderInfo.tenderInfoId +">["+row.docManage.docCode+"]" +row.docManage.docName + "</option>");
        $("#tenderInfoId").trigger('change');
    } else {
        var result = client.callAsJson("tenderPreparationService/querySuccTendInfoListForNotice", param);
//  result.result.unshift({'id':'','text':'全部'});
//$('#tenderInfoId').append("<option value=''>全部</option>");
        $.each(result.result, function (i) {
            $('#tenderInfoId').append("<option value=" + result.result[i].tenderInfoId + ">[" + result.result[i].docCode + "]" + result.result[i].docName + "</option>");
            bidMap[result.result[i].tenderInfoId] = result.result[i];
//   result.result[i].id=result.result[i].tenderInfoId;
//   result.result[i].text="["+result.result[i].docCode+"]" +result.result[i].docName;
        });
        $("#tenderInfoId").select2({});
    }
}

function initOrg(){
    $("#orgList").empty();
    var client = new com.im.common.ajax();
    var result = client.callAsJson("userService/queryOrgarizationsByCond", {"forOrgList": "","notOrgType":10});

    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        console.log(result);
        result.result.unshift({'orgId':'','orgName':'请选择'});
        $.each( result.result, function (i) {
            $('#orgList').append("<option value=" + result.result[i].orgId + ">" +result.result[i].orgName + "</option>");

        });
        $("#orgList").select2({});
        $("#orgList").select2().trigger("change");
    }
}

function initStatusCdQry(){
    var client = new com.im.common.ajax();
    var param={};
    param.tabName="T_NOTICE_MANAGE";
    param.colName="STATUS_CD";
    var result = client.callAsJson("commonService/queryTabColParam",param);
    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        result.result.unshift({'colVal':'','colValName':'全部'});
        $.each( result.result, function (i) {
            $('#statusCdQry').append("<option value=" + result.result[i].colVal + ">" +result.result[i].colValName + "</option>");
        });
        $("#statusCdQry").select2({});
    }
}

function newNoticeInfo(){
    $('#addEditModal').modal("show");
    var client = new com.im.common.ajax();
    var param={};
    param.tableName="T_NOTICE_MANAGE";
    var result = client.callAsJson("commonService/getSeq",param);
    if(result.resultCode!=0){
        toastr.error(result.resultCode);
    }else{
        console.log(result.result.seq);
        $("#noticeNo").val(result.result.seq);
    }
}

function saveNoticeInfo(){
    var noticeManageId=$("#noticeManageId").val();
    var param = {};
    var url="noticeManageService/updateNoticeManage";
    if(noticeManageId==null || noticeManageId=="" || noticeManageId==undefined){
        url="noticeManageService/addNoticeManage";
    }else{
        param.contractId=$("#contractId").val();
        param.noticeManageId=noticeManageId;//通知书管理id
    }
    // param.noticeName=$("#tenderInfoId").find("option:selected").text();
    param.noticeName=$("#myFileName").val();
    param.orgId=$("#orgList").val();//承接商id
    param.money=$("#money").val();//中标金额
    param.purchPlanId=$("#purchPlanId").val();//采购计划ID
    param.tenderInfoId=$("#tenderInfoId").val();//标书id
    param.impleProjId =$("#implProId").val();///项目ID
    param.publicityDt=$("#openDt").val();//公布时间
    param.fileRec=$("#fileCount").val();//投标文件数量
    param.fileType=$("#fileType").val();//文件类型
    param.description=$("#description").val();//备注信息
    param.noticeCode=$("#noticeNo").val();//通知编码
    param.statusCd=$("#statusCd").val();
    //通知书名称和编码+通知书发放时间

    var formValidator = $('#letterForm').data('bootstrapValidator');
    formValidator.options.excluded = [ ':hidden',':not(:visible)','disabled'];
    formValidator.validate();
    if (formValidator.isValid()) {
        if(param.money > $("#prepayTotal").val()) {
            toastr.error('中标金额不能大于采购计划预算金额');
            return ;
        }

        param.noticeFile=fileInfo;
        var fileList = [];
        var delFiles = [];
        var client = new com.im.common.ajax();
        //上传文件
        var filename = $('#common_file_name label');
        var files = [];
        for (var i = 0; i < filename.length; i++) {
            if (filename.eq(i).is(':visible')) {
                files.push(filename.eq(i).html());
            }
        }

        if(tmpfiles.del!=null && tmpfiles.del.length>0){
            delFiles=tmpfiles.del;
        }
        param.delFiles=delFiles;
        if (filename.length > 0) {

            client.callAsFile(tmpfiles.newly, function (result) {
                if (!result.success) {
                    toastr.error('文件上传失败！');
                    return false;
                } else {
                    $.each(result.result, function (index, item) {
                        fileList.push(item);
                    });
                    param.fileList = fileList;
                    console.log(param);
                    var result = client.callAsJson(url, param);
                    if (result.resultCode != 0) {
                        toastr.error(result.resultCode);
                    } else {
                        $('#addEditModal').modal('hide');
                        queryNoticeInfo();
                    }
                }
            });
        }else{
            console.log(param);
            var result = client.callAsJson(url, param);
            if (result.resultCode != 0) {
                $('#addEditModal').modal('hide');
                toastr.error("修改失败");
            } else {
                $('#addEditModal').modal('hide');
                queryNoticeInfo();
            }
        }
        //getBidDocInfo();
    }
}

function showDetailInfo(tenderInfoId){
    if(modalType=='add'){
        var info=bidMap[tenderInfoId];
        if(info!=undefined && info!=null){
            $("#implProjectInfo").val(info.impleProjName);
            $("#purchPlan").val(info.purchPlanName);
            $("#purchPlanId").val(info.purchPlanId);
        }else{
            $("#implProjectInfo").val("");
            $("#purchPlan").val("");
            $("#purchPlanId").val("");
        }
    }
}

function delNoticeManageConfirm(index){
    var row = $('#letterList').datagrid('getData').rows[index];
    var param={};
    param.noticeManageId=row.noticeManage.noticeManageId;
    if(row.noticeManage!=null && row.noticeManage.contractStatusCd!=null && (row.noticeManage.contractStatusCd==20 || row.noticeManage.contractStatusCd==30)) {
        toastr.warn("已签订的合同的中标通知书不能删除");
    }else{
        com.im.common.confirm('确认删除中标通知书？', param, "delNotice");
    }
}

function delNotice(param){
    var url = "/noticeManageService/deleteNoticeManage";
    var client = new com.im.common.ajax();
    var result = client.callAsJson(url,param);
    if(!result.success) {
        toastr.error(result.resultMsg);
    }else{
        queryNoticeInfo();
    }
}


function queryNoticeInfo(){
    defaultParameter.orgId=$("#orgId").val();
    defaultParameter.planProjClass=$("#planProjClass").val();
    defaultParameter.implProjectId=$("#implProjectId").val();
    defaultParameter.statusCdQry=$("#statusCdQry").val();
    $('#letterList').datagrid("load",defaultParameter);
}

function _initOrgType(){
    var result = client.callAsJson("userService/queryOrgarizationsByCond", { "hasOrgType":'Y'});
    if(result.success){
        orgTypes = result.result;
        $("#selectOrgType").append("<option value=''>全部</option>");
        $("#orgTypeSel").append("<option value=''>请选择</option>");
        $.each(orgTypes,function(i,obj){
            $("#selectOrgType").append("<option value='"+obj.id+"'>"+obj.text+"</option>"); ;
            $("#orgTypeSel").append("<option value='"+obj.id+"'>"+obj.text+"</option>"); ;
        });
    }else{
        toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
    }
    $('#orgTypeSel').select2();
};

function initContractStatus(){
    var client = new com.im.common.ajax();
    var param={};
    param.tabName="T_NOTICE_MANAGE";
    param.colName="STATUS_CD";
    var result = client.callAsJson("commonService/queryTabColParam",param);
    if(!result.success){
        toastr.error(result.resultMsg);
    }else{
        $.each( result.result, function (i) {
            $('#statusCd').append("<option value=" + result.result[i].colVal + ">" +result.result[i].colValName + "</option>");
        });
        $("#statusCd").select2({});
    }
}

function _saveOrUpdate(){

    $("#unitForm").bootstrapValidator('validate');//提交验证
    if (!$("#unitForm").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码
        return;
    }

    var orgName =  $("#orgNameInput").val();
    if(orgName == undefined || orgName == ''){
        toastr.warning("请填写单位名称！！");
        return;
    }
    var orgType =  $("#orgTypeSel").val();
    if(orgType == undefined || orgType == ''){
        toastr.warning("请选择单位类型！！");
        return;
    }
    var orgAddr = $("#orgAddrInput").val();
    // if(orgAddr == undefined || orgAddr == ''){
    //     toastr.warning("请填写单位地址！！");
    //     return;
    // }
    var orgTel = $("#orgTelInput").val();
    // if(orgTel == undefined || orgTel == ''){
    //     toastr.warning("请单位联系方式！！");
    //     return;
    // }
    var orgFax =  $("#orgFaxInput").val();
    var orgEmail =  $("#orgEmailInput").val();

    var linkMan = $("#linkManInput").val();
    // if(linkMan == undefined || linkMan == ''){
    //     toastr.warning("请填写单位联系人！！");
    //     return;
    // }
    var linkManTel =  $("#linkManTelInput").val();
    // if(linkManTel == undefined || linkManTel == ''){
    //     toastr.warning("请填写单位联系人电话！！");
    //     return;
    // }
    var linkManPhone = $("#linkManPhoneInput").val();
    // if(linkManPhone == undefined || linkManPhone == ''){
    //     toastr.warning("请填写单位联系人手机号码！！");
    //     return;
    // }
    var linkManEmail = $("#linkManEmailInput").val();
    // if(linkManEmail == undefined || linkManEmail == ''){
    //     toastr.warning("请填写联系人邮箱！！");
    //     return;
    // }

    var uparam = {};
    var orgparam = {};
    orgparam.orgName = orgName;
    orgparam.orgType = orgType;
    orgparam.orgAddr = orgAddr;
    orgparam.orgTel = orgTel;
    orgparam.orgEmail = orgEmail;
    orgparam.orgFax = orgFax;
    orgparam.linkMan = linkMan;
    orgparam.linkManTel = linkManTel;
    orgparam.linkManPhone = linkManPhone;
    orgparam.linkManEmail = linkManEmail;
    orgparam.orgName = orgName;
    orgparam.operType = "add";
    uparam.org = orgparam;

    var result = client.callAsJson("userService/saveOrUpdateOrg", uparam);
    if(result.success){
        $("#unitAddModal").modal("hide");
        initOrg();
        toastr.info("操作成功！");
    }else{
        toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
    }
}

function formFormatter(){
    $("#letterForm").bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-loadData'
        },
        excluded: [ ':hidden',':not(:visible)','disabled'],
        fields: {
            tenderInfoId: {
                validators: {
                    notEmpty: {
                        message: '请选择招标信息'
                    },
                }
            },
            implProjectInfo :{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择实施项目'
                    },
                }
            },
            orgList: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择中标单位'
                    },
                }
            },
            openDt: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请选择公布时间'
                    },
                }
            },

            money: {
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '请输入中标金额'
                    },
                    regexp: {
                        regexp:/^[1-9][0-9]*(.[0-9]{1,4})?$/ ,
                        message: '中标金额必须为正数,最多保留四位小数'
                    },

                }
            },

        }
    });
}



$(function(){
    $('#batchTrial').click(function (){
        if($('#letterList').datagrid('getChecked').length == 0) {
            com.im.common.confirm("请选择项目", null, function () {
                return;
            });
        } else {
            var noticeManageIds = [];
            var impleProjIds =[];
            var i = 0;
            $.each($('#letterList').datagrid('getChecked'), function(index, item){
                if(item.noticeManage!=null){
                    noticeManageIds[i] = item.noticeManage.noticeManageId;
                    impleProjIds[i] = item.implementProject.impleProjId;
                    i++;
                }
            });

            var saveparam={};
            saveparam.noticeManageIds = noticeManageIds;
            saveparam.impleProjIds = impleProjIds;
            saveparam.statusCd = 20;
            var client = new com.im.common.ajax();
            var result = client.callAsJson("noticeManageService/updateNoticeManageByBatch", saveparam);
            if(result.resultCode=='0'){
                toastr.success("批量审定成功！");
                queryNoticeInfo();
            }else {
                toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
            }
        }
    });

    $("#orgId").project2unit2itemCommpent({
        //elmIdProjectSel : "projectSel",//规划工程下拉元素
        elmIdPlanTypeSel : "planProjClass",
        elmIdUnitSel : "orgId",//组织单位下拉元素
        elmIdItemSel : "implProjectId",//实施项目下拉元素
        orgType : "10",//初始化单位时，单位类型
        callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
            queryNoticeInfo();
        }
    });

    // $("#orgIdInfo").project2unit2itemCommpent({
    //   //elmIdProjectSel : "projectSel",//规划工程下拉元素
    //   elmIdPlanTypeSel : "planProjClassInfo",
    //   elmIdUnitSel : "orgIdInfo",//组织单位下拉元素
    //   elmIdItemSel : "implProjectInfo",//实施项目下拉元素
    //   orgType : "",//初始化单位时，单位类型
    //   callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
    //     //_callBackOrg(objvalue, objname);
    //     //callBackType : 1 所属规划值变更 2单位值变更  3项目名称变更
    //     //ret: orgId,orgName,impleProjId,impleProjName,planProjClass,planProjClassName
    //   }
    // });

    // $("#orgIdInfo").bind('change', function () {
    //     initImpleProj();
    // });

    // $("#planProjClassInfo").bind('change', function () {
    //     initImpleProj();
    // });

    // $("#implProjectInfo").bind('change', function () {
    //   initPurchPlan({impleProjId: $(this).val()});
    //     getBidDocInfo();
    // });

    $("#userBtn").click(function() {
        $("#orgInfo").userSearchCommpent({
            elmIdOut : "orgInfo",//组织树单击之后回填的文本框（input）
            elmIdModal : "userSearchModal",//用户选择
            elmIdOrgModal : "unitSearchModal",//组织查询
            callbackFunc: function (staffId, staffName) {//组织树单击之后回调函数
                _callBackOrg(staffId, staffName);
            }
        });
    });

    //时间插件
    $('#startDatepicker').datepicker({
        onSelect:function (){
            $('#startDatepicker').trigger("change");
        }
    });

    $('.datetimepicker').datepicker({
        onSelect:function (){
            $('.datetimepicker').trigger("change");
        }
    });

    initFileType();

    initTable();

    initPlan();

    initStatusCdQry();

    $("#statusCdQry").change(function(){
        queryNoticeInfo();
    });

    //getBidDocInfo();

    _initOrgType();

    initContractStatus();

    $("#addUnitBtn").click(function(){
        _saveOrUpdate();
    });


    $("#tenderInfoId").on("change",function(){
        var data = $(this).val();
        showDetailInfo(data);
    });

    $("#addUnit").click(function(){
        $('#unitAddModal').modal("show");
    });


    $('#myFile').change(function (){
        var reg = /[^\\\/]*[\\\/]+/g;
        $('#myFileName').val($(this).val().replace(reg, ''));
    });

    $("#fileBtn").click(function(){
        uploadFile();
    });

    // $('#purchPlan').bind('change',function(){
    //   getBidDocInfo();
    // });

    initOrg();

    $("#saveBtn").click(function(){
        saveNoticeInfo();
    });

    $("#addNoticeBtn").click(function(){
        newNoticeInfo();
    });

//    $('#addEditModal').on('show.bs.modal', function () {
//    if($("#tenderInfoArea").attr("type")=="update"){
//      $("#tenderInfoArea").empty();
//      $("#tenderInfoArea").attr("type","add");
//      $("tenderInfoArea").append("<label  for='tenderInfoId' class='control-label'>标书信息：</label><select class='form-control select2' id='tenderInfoId' name='tenderInfoId'></select>");
//      getBidDocInfo();
//      }
//      });

    $('#addEditModal').on('hidden.bs.modal', function () {
        $("#noticeManageId").val("");
        $("#contractId").val("");
        $("#purchPlanId").val("");
        $("#tenderInfoId").val("").trigger("change");
        modalType='add';
        // $("#planProjClassInfo").val("").trigger("change");
        // $("#implProjectInfo").val("").trigger("change");
        // $("#purchPlan").val("").trigger("change");
        $("#orgList").val("").trigger("change");

        $('#letterForm').data('bootstrapValidator').options.excluded = [':disabled'];
        $('#letterForm').bootstrapValidator('resetForm', true);
        file.activate(1)
        $("#common_file_bnt").text("添加招标文件");
        $('#letterForm')[0].reset();

        ableField();
        $("#letterForm").data('bootstrapValidator').destroy();
        $('#letterForm').data('bootstrapValidator', null);
        formFormatter();
        $('#addEditModal .modal-title').html('通知书增加');
    });

    formFormatter();

    $("#unitForm").bootstrapValidator({
        live: 'enabled',
        excluded: [':hidden'],
        feedbackIcons: {valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-loadData'},
        fields: {
            orgNameInput : {validators: {notEmpty: {message: "请填写单位名称."}}}
            ,orgTypeSel : {validators: {notEmpty: {message: "请选择单位类型."}}}
            //,orgAddrInput : {validators: {notEmpty: {message: "请填写单位地址."}}}
            //,orgTelInput : {validators: {notEmpty: {message: "请填写单位电话."}}}
            //,linkManInput : {validators: {notEmpty: {message: "请填写联系人."}}}
            ,linkManTelInput : {validators:
                {//notEmpty: {message: "请填写联系人手机."},
                    regexp: {
                        regexp: /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/,
                        message: '手机号码格式有误.'
                    }}}
            //,linkManPhoneInput : {validators: {notEmpty: {message: "请填写联系人电话."}}}
            ,linkManEmailInput : {validators: {
                //notEmpty: {message: "请填写邮箱地址."},
                emailAddress: {message: "邮箱格式有误."}}}
        }
    });
})